<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>教材管理</el-breadcrumb-item>
      <el-breadcrumb-item>教材信息</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区-->
    <el-card>
      <!--搜索与添加-->
      <el-row :gutter="10">
        <el-col :span="8">
          <el-select v-model="queryInfo.campusId" placeholder="请选择" style="width: 100%" clearable @clear="getBookList">
            <el-option
              v-for="item in campuses"
              :key="item.id"
              :label="item.id"
              :value="item.id">
              <span style="float: left">{{ item.id }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" icon="el-icon-search" @click="selectByCampus"></el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true" >添加教材</el-button>
        </el-col>
      </el-row>
      <!--教材列表区域-->
      <el-table :data="bookList" class="tableBox" border stripe>
        <el-table-column  align="center" label="序号" type="index"></el-table-column>
        <el-table-column  align="center" label="教材名称" prop="bookName"></el-table-column>
        <el-table-column  align="center" label="ISBN" prop="isbn"></el-table-column>
        <el-table-column  align="center" label="出版社" prop="publisher"
                          :filters="publish" :filter-method="filterPublish" filter-placement="bottom-end"></el-table-column>
        <el-table-column  align="center" label="出版日期" prop="date"
                          :filters="year" :filter-method="filterYear" filter-placement="bottom-end"></el-table-column>
        <el-table-column  align="center" label="作者" prop="author"></el-table-column>
        <el-table-column  align="center" label="操作" width="120px">
          <template slot-scope="scope">
            <!--修改-->
            <el-button type="primary" icon="el-icon-edit" circle @click="showEditDialog(scope.row.isbn)"></el-button>
            <!--删除-->
            <el-button type="danger" icon="el-icon-delete" circle @click="removeBookById(scope.row.isbn)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!--添加教材的对话框-->
      <el-dialog
        title="添加教材"
        :visible.sync="addDialogVisible"
        @close="addDialogClosed"
        width="30%">
        <!--内容主体区域-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
          <el-form-item label="书名" prop="bookName">
            <el-input v-model="addForm.bookName"></el-input>
          </el-form-item>
          <el-form-item label="ISBN" prop="isbn">
            <el-input v-model="addForm.isbn"></el-input>
          </el-form-item>
          <el-form-item label="出版社" prop="publisher">
            <el-input v-model="addForm.publisher"></el-input>
          </el-form-item>
          <el-form-item label="出版日期" prop="date">
            <div class="block">
              <el-date-picker
                v-model="addForm.date"
                type="month"
                value-format="yyyy-MM"
                placeholder="选择月">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-select v-model="addForm.author" multiple placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in teachers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                <span style="float: left">{{ item.id }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px; margin-right: 24px">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addBook">确 定</el-button>
        </span>
      </el-dialog>

      <!--修改用户的对话框-->
      <el-dialog
        title="修改教材"
        :visible.sync="editDialogVisible"
        width="30%"
        @close="editDialogClosed">
        <!--内容主体区域-->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
          <el-form-item label="书名" prop="bookName">
            <el-input v-model="editForm.bookName"></el-input>
          </el-form-item>
          <el-form-item label="教材编号" prop="isbn">
            <el-input v-model="editForm.isbn" disabled></el-input>
          </el-form-item>
          <el-form-item label="出版社" prop="publisher">
            <el-input v-model="editForm.publisher"></el-input>
          </el-form-item>
          <el-form-item label="出版日期" prop="date">
            <div class="block">
              <el-date-picker
                v-model="editForm.date"
                type="month"
                value-format="yyyy-MM"
                placeholder="选择月">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-select v-model="editForm.author" multiple placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in teachers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                <span style="float: left">{{ item.id }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px; margin-right: 24px">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editBook">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
const unique = (arr, key) => {
  let result = {};
  for (let item of arr) {
    result[item[key]] = item;
  }
  return Object.values(result); // 再转化为数组
}
export default {
  data () {
    return {
      publish: [],
      year: [],
      teachers: [],
      campuses: [],
      books: [],
      //  获取用户列表参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
        campusId: ''
      },
      bookList: [],
      total: 0,
      //  控制对话的显示
      addDialogVisible: false,
      //  添加用户的表单数据
      addForm: {
        bookName: '',
        isbn: '',
        date: '',
        publisher: '',
        author: ''
      },
      //  添加表单的验证规则对象
      addFormRules: {
        bookName: [
          { required: true, message: '请输入教材名称', trigger: 'blur' }
        ],
        isbn: [
          { required: true, message: '请输入教材编号', trigger: 'blur' }
        ],
        publisher: [
          { required: true, message: '请输入出版社', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请输入出版日期', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ]
      },
      //  修改表单的验证规则对象
      editFormRules: {
        bookName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' }
        ],
        isbn: [
          { required: true, message: '请输入教材编号', trigger: 'blur' }
        ],
        publisher: [
          { required: true, message: '请输入出版社', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请输入出版日期', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ]
      },
      //  控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      //  查询到的用户信息对象
      editForm: {
        bookName: '',
        isbn: '',
        date: '',
        publisher: '',
        author: ''
      }
    }
  },
  created () {
    this.getCampusList()
    this.getTeacherList()
    this.getBookList()
  },
  methods: {
    async selectByCampus () {
      if (this.queryInfo.campusId === '') {
        return this.getBookList()
      }
      const { data: res } = await this.$http.get(`/teacher/findByCampusIdEquals?campusId=${this.queryInfo.campusId}`)
      this.bookList = []
      for (let i = 0; i < res.data.length; i++) {
        const {data: res2} = await this.$http.get(`/book/findByTeacherId?teacherId=${res.data[i].teacherId}`)
        if (res2.data.length === 0) {
          continue
        }
        for (let j = 0; j < res2.data.length; j++) {
          let authName = []
          let name = ''
          for (let k = 0; k < res2.data[j].author.length; k++) {
            const { data: teacher } = await this.$http.get(`/teacher/findByTeacherIdEquals?teacherId=${res2.data[j].author[k]}`)
            if (teacher.code === 404) {
              continue
            }
            if (k !== res2.data[j].author.length - 1) {
              name = teacher.data.teacherName + ' '
            } else {
              name = teacher.data.teacherName
            }
            authName.push(name)
          }
          res2.data[j].author = authName
        }
        this.bookList.push(res2.data[0])
        this.bookList = this.bookList.filter(n => n).sort(
          function (a, b) {
            return a.isbn > b.isbn ? 1 : -1
          }
        )
      }
    },
    async getCampusList () {
      this.campuses = []
      let result
      const { data: res } = await this.$http.get('/campus/findAll')
      if (res.code !== 200) {
        return this.$message.error('获取学院列表失败')
      }
      result = res.data.filter(n => n).sort(
        function (a, b) {
          return a.campusId > b.campusId ? 1 : -1
        }
      )
      for (let i = 0; i < result.length; i++) {
        this.campuses.push({
          key: i,
          name: result[i].campusName,
          id: result[i].campusId,
        })
      }
    },
    filterPublish(value, row) {
      return row.publisher === value;
    },
    filterYear(value, row) {
      return row.date.split('-')[0] === value;
    },
    async getTeacherList () {
      let result
      const { data: res } = await this.$http.get('/teacher/findAll')
      if (res.code !== 200) {
        return this.$message.error('获取教师列表失败')
      }
      result = res.data.filter(n => n).sort(
        function (a, b) {
          return a.teacherId > b.teacherId ? 1 : -1
        }
      )
      for (let i = 0; i < result.length; i++) {
        this.teachers.push({
          key: i,
          name: result[i].teacherName,
          id: result[i].teacherId
        })
      }
    },
    async getBookList () {
      const { data: res } = await this.$http.get('/book/findAll')
      if (res.code !== 200) {
        return this.$message.error('获取教材列表失败')
      }
      for (let i = 0; i < res.data.length; i++) {
        let authName = []
        let name = ''
        for (let j = 0; j < res.data[i].author.length; j++) {
          const { data: teacher } = await this.$http.get(`/teacher/findByTeacherIdEquals?teacherId=${res.data[i].author[j]}`)
          if (teacher.code === 404) {
            continue
          }
          if (j !== res.data[i].author.length - 1) {
            name = teacher.data.teacherName + ' '
          } else {
            name = teacher.data.teacherName
          }
          authName.push(name)
        }
        res.data[i].author = authName
      }
      this.publish = []
      for (let i = 0; i < res.data.length; i++) {
        this.publish.push({
          text: res.data[i].publisher,
          value: res.data[i].publisher
        })
      }
      this.publish = unique(this.publish, 'text')
      this.year = []
      for (let i = 0; i < res.data.length; i++) {
        this.year.push({
          text: res.data[i].date.split('-')[0],
          value: res.data[i].date.split('-')[0]
        })
      }
      this.year = unique(this.year, 'text')

      this.bookList = res.data.filter(n => n).sort(
        function (a, b) {
          return a.isbn > b.isbn ? 1 : -1
        }
      )
      this.total = res.data.length
    },
    //  监听Pagesize
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getBookList()
    },
    // 监听页码值改变
    handleCurrentChange (newPage) {
      this.queryInfo.pagesize = newPage
      this.getBookList()
    },
    //  监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    //  监听修改用户对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    //  点击按钮添加新用户
    addBook () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //  可以发起添加用户的网络请求
        const {data: res} = await this.$http.post('/book/insert', this.addForm)
        if (res.code !== 200) {
          return this.$message.error('添加教材失败！')
        }
        this.$message.success('添加教材成功!')
        //  隐藏添加用户的对话框
        this.addDialogVisible = false
        //  重新获取用户列表数据
        await this.getBookList()
      })
    },
    //  展示编辑用户的对话框
    async showEditDialog (id) {
      const {data: res} = await this.$http.get(`book/findByisbnEquals?isbn=${id}`)
      if (res.code !== 200) {
        return this.$message.error('获取教材信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    //  修改用户信息并提交
    editBook () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.post('book/update', this.editForm)
        if (res.code !== 200) {
          return this.$message.error('修改教材信息失败！')
        }
        this.$message.success('修改教材信息成功!')
        //  隐藏添加用户的对话框
        this.editDialogVisible = false
        //  重新获取用户列表数据
        await this.getBookList()
      })
    },
    //  根据id删除对应的用户信息
    async removeBookById (id) {
      //  弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.get(`book/delete?isbn=${id}`)
      if (res.code !== 200) {
        return this.$message.error('删除教材失败！')
      }
      this.$message.success('删除教材成功！')
      this.getBookList()
    }
  }
}
</script>

<style lang="less" scoped>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
</style>
